package cc.linker.steplink.crm.merchanth5.controller;

import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.service.EnrollActiveService;
import cc.linker.steplink.crm.merchanth5.service.OverViewInfoService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/h5/enrollactive")
public class EnrollActiveController {

    @Autowired
    private EnrollActiveService enrollActiveService;

    @Autowired
    private RequestFilter requestFilter;

    @Autowired
    private OverViewInfoService overViewInfoService;


    /**
     * 新表单获取签名
     * @param param
     * @return
     */
    @PostMapping("/getsign")
    public Map<String,Object> getSign(@RequestBody Map<String, String> param){
        return enrollActiveService.getSignNew(param);
    }


    /**
     * 报名数据统计
     * @param param
     */
    @PostMapping("/datasummary")
    public void dataSummary(@RequestBody Map<String, String> param) {
        String enrollId = param.get("formId");//活动Id
        String customerId = param.get("customerId");//用户Id
        String orgId = param.get("orgId");//机构Id
        int optionPrice = Integer.valueOf(param.get("fee"));//费用（单位分）
        int type = Integer.valueOf(param.get("type"));//1：点击，2：分享，3：购买，4：购物车加入
        if (StringUtils.isEmpty(enrollId) || StringUtils.isEmpty(customerId) || StringUtils.isEmpty(orgId)
                || StringUtils.isEmpty(optionPrice) || StringUtils.isEmpty(type)) {
            throw GlobalException.build("参数错误");
        }
        overViewInfoService.goodsData(null, enrollId, type, null, null,
                null, 1, optionPrice, customerId, orgId, null);
    }


    /**
     * 获取活动详情
     * @param enrollId
     * @param request
     * @return
     */
    @GetMapping("/getinfo")
    public Map<String,Object> getInfo(@RequestParam String enrollId, HttpServletRequest request){
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        if(StringUtils.isEmpty(enrollId)){
            throw GlobalException.build("参数错误");
        }
        Map<String,Object> param = new HashMap<>(2);
        param.put("orgId",orgId);
        param.put("enrollId",enrollId);
        return enrollActiveService.getInfo(param);
    }


    /**
     * 保存报名信息
     * @param request
     * @param param
     * @return
     */
    @PostMapping("/saverecord")
    public Map saveRecord(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        if (StringUtils.isEmpty(param.get("enrollId")) || StringUtils.isEmpty(param.get("optionId")) || StringUtils.isEmpty(param.get("record"))) {
            throw GlobalException.build("参数错误");
        }
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        String customerId = wxUser.getCustomerId();
        param.put("orgId", orgId);
        param.put("customerId", customerId);
        param.put("openId",wxUser.getPayOpenId());
//        param.put("openId",wxUser.getOpenid());
        enrollActiveService.getRecordAttr(param);
        param.put("record", JSON.serialize(param.get("record")));

        if(StringUtils.isEmpty(param.get("orderSource"))){
            param.put("orderSource",1);
        }

        if(StringUtils.isEmpty(param.get("id"))){
            Map<String, Object> enrollBase = enrollActiveService.getEnrollBase(param);
            if("0".equals(enrollBase.get("isRepeat").toString())){
                //不允许重复报名
                int customerRecordCount = enrollActiveService.getCustomerRecordCount(param);
                if(customerRecordCount > 1){
                    throw GlobalException.build("请勿重复报名");
                }
            }
            //不传id表示新增
            return enrollActiveService.addRecord(param,false);
        }else{
            //编辑
            Map<String,Object> customerRecord = enrollActiveService.getCustomerRecordMap(param);
            int toPay = 0;
            if("1".equals(customerRecord.get("payStatus"))){
                if (!(customerRecord.get("optionId").equals(param.get("optionId")))) {
                    throw GlobalException.build("非法操作");
                }
            }else{
                toPay = 1;
            }
            param.put("oldOptionId",customerRecord.get("optionId"));
            return enrollActiveService.updateRecord(param,toPay);
        }
    }

    /**
     * 1.11.26 app
     * 通联模式根据orderSn和openId 生成 签名
     * @param param
     * fl
     * @return
     */
    @PostMapping("/payrecord")
    public Map payRecord( @RequestBody Map<String, Object> param) {
        if (StringUtils.isEmpty(param.get("orderSn")) || StringUtils.isEmpty(param.get("openId"))) {
            throw GlobalException.build("参数错误");
        }
        Map<String,Object> res = new HashMap<>();
        res.put("sign",enrollActiveService.payRecord(param));
        return res;
    }

    /**
     * 获取我的报名信息
     * @param request
     * @param enrollId
     * @return
     */
    @GetMapping("/getmyrecord")
    public Map<String,Object> getMyRecord(HttpServletRequest request,
                                          @RequestParam String enrollId,
                                          @RequestParam(value = "id", defaultValue = "", required = false) String id){
        if(StringUtils.isEmpty(enrollId)){
            throw GlobalException.build("参数错误");
        }
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId= wxUser.getOrgId();
        Map<String,Object> param = new HashMap<>(3);
        param.put("enrollId",enrollId);
        param.put("customerId",customerId);
        param.put("orgId",orgId);
        if(!StringUtils.isEmpty(id)){
            param.put("id",id);
        }
        Map<String,Object> res = new HashMap<>();
        Map<String,Object> customerRecord = enrollActiveService.getMyCustomerRecord(param);
        if(null == customerRecord){
            return new HashMap<>();
        }
        Map<String, Object> enrollBase = enrollActiveService.getEnrollBase(param);
        res.put("record",customerRecord);
        res.put("enroll",enrollBase);
        res.put("option",enrollActiveService.getOptionByOptionId((String)customerRecord.get("optionId")));
        return res;
    }


    /**
     * 获取我的报名列表
     * @param request
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/getmyenrolllist")
    public PageInfo getMyEnrollList(HttpServletRequest request,
                                    @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                    @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize){
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId= wxUser.getOrgId();
        Map<String,String> param = new HashMap<>();
        param.put("customerId",customerId);
        param.put("orgId",orgId);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(enrollActiveService.getMyEnrollList(param));
    }

}
